﻿using System;
using System.Net;
using System.Threading;

namespace Comdiv.QWeb.Remoting {
	public abstract class ConnectionBase : IQWebConnection {
		protected ICredentials credentials;

		#region IQWebConnection Members

		public void SetCredentials(ICredentials credentials) {
			this.credentials = credentials;
		}

		public QWebResult Call(QWebQuery query) {
			lock (this) {
				return internalCall(query);
			}
		}

		public void Call(QWebQuery query, Action<QWebResult> callback) {
			ThreadPool.QueueUserWorkItem(s =>
			                             	{
			                             		var ac = (asynccall) s;
			                             		var result = Call(ac.query);
			                             		ac.callback(result);
			                             	}, new asynccall {query = query, callback = callback});
		}

		#endregion

		protected abstract QWebResult internalCall(QWebQuery query);

		#region Nested type: asynccall

		private struct asynccall {
			public Action<QWebResult> callback;
			public QWebQuery query;
		}

		#endregion
	}
}